package com.panda.framework.web.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.panda.common.constant.CacheConstants;
import com.panda.common.constant.Constants;
import com.panda.common.constant.UserConstants;
import com.panda.common.core.domain.entity.SysUser;
import com.panda.common.core.domain.model.LoginUser;
import com.panda.common.core.redis.RedisCache;
import com.panda.common.exception.ServiceException;
import com.panda.common.exception.user.BlackListException;
import com.panda.common.exception.user.CaptchaException;
import com.panda.common.exception.user.CaptchaExpireException;
import com.panda.common.exception.user.UserNotExistsException;
import com.panda.common.exception.user.UserPasswordNotMatchException;
import com.panda.common.utils.DateUtils;
import com.panda.common.utils.MessageUtils;
import com.panda.common.utils.StringUtils;
import com.panda.common.utils.ip.IpUtils;
import com.panda.framework.manager.AsyncManager;
import com.panda.framework.manager.factory.AsyncFactory;
import com.panda.framework.security.context.AuthenticationContextHolder;
import com.panda.system.service.ISysConfigService;
import com.panda.system.service.ISysUserService;

import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author panda
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Value("${token.loginStatus}")
    private boolean loginStatus;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, String platform) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
//        if (captchaEnabled) {
//            validateCaptcha(username, code, uuid);
//        }
        if (false) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        loginUser.setPlatform(platform);
        recordLoginInfo(loginUser.getUserId());
        // 添加到这里
        // 判断是否允许账户多终端同时登录
        if (!loginStatus) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            if (Objects.equals(platform, "2")) {//如果platform 是2说明是APP
                String userIdKey = Constants.LOGIN_USER_KEY + Constants.APP + loginUser.getUser().getUserId();
                String userKey = redisCache.getCacheObject(userIdKey);
                if (StringUtils.isNotEmpty(userKey)) {
                    redisCache.deleteObject(userIdKey);
                    redisCache.deleteObject(userKey);
                }
            } else {//PC
                String userIdKey = Constants.LOGIN_USER_KEY + loginUser.getUser().getUserId();
                String userKey = redisCache.getCacheObject(userIdKey);
                if (StringUtils.isNotEmpty(userKey)) {
                    redisCache.deleteObject(userIdKey);
                    redisCache.deleteObject(userKey);
                }
            }

        }
        // 生成token
        return tokenService.createToken(loginUser);
//        // 验证码校验
//        validateCaptcha(username, code, uuid);
//        // 登录前置校验
//        loginPreCheck(username, password);
//        // 用户验证
//        Authentication authentication = null;
//        try
//        {
//            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
//            AuthenticationContextHolder.setContext(authenticationToken);
//            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
//            authentication = authenticationManager.authenticate(authenticationToken);
//        }
//        catch (Exception e)
//        {
//            if (e instanceof BadCredentialsException)
//            {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//                throw new UserPasswordNotMatchException();
//            }
//            else
//            {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
//                throw new ServiceException(e.getMessage());
//            }
//        }
//        finally
//        {
//            AuthenticationContextHolder.clearContext();
//        }
//        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        recordLoginInfo(loginUser.getUserId());
//
//        // 添加到这里
//        // 判断是否允许账户多终端同时登录
//        if (!soloLogin)
//        {
//            // 如果用户不允许多终端同时登录，清除缓存信息
//            String userIdKey = Constants.LOGIN_USER_KEY + loginUser.getUser().getUserId();
//            String userKey = redisCache.getCacheObject(userIdKey);
//            if (StringUtils.isNotEmpty(userKey))
//            {
//                redisCache.deleteObject(userIdKey);
//                redisCache.deleteObject(userKey);
//            }
//        }
    }

//    /**
//     * 公众号生成Token
//     * @param openId
//     * @param platform
//     * @return
//     */
//    public String weChatLogin(String openId, String platform) {
//        // 用户验证
//        Authentication authentication = null;
//        try {
////            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(openId, openId);
////            AuthenticationContextHolder.setContext(authenticationToken);
////            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
////            authentication = authenticationManager.authenticate(authenticationToken);
//        } catch (Exception e) {
//            if (e instanceof BadCredentialsException) {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(openId, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//                throw new UserPasswordNotMatchException();
//            } else {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(openId, Constants.LOGIN_FAIL, e.getMessage()));
//                throw new ServiceException(e.getMessage());
//            }
//        } finally {
//            AuthenticationContextHolder.clearContext();
//        }
//        AsyncManager.me().execute(AsyncFactory.recordLogininfor(openId, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
////        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
////        loginUser.setPlatform(platform);
////        recordLoginInfo(Long.parseLong(openId));
//        if (!loginStatus) {
//            // 如果用户不允许多终端同时登录，清除缓存信息
//                String userIdKey = Constants.WeCHAT_LOGIN_USER_KEY + Constants.GZH + loginUser.getUser().getUserId();
//                String userKey = redisCache.getCacheObject(userIdKey);
//                if (StringUtils.isNotEmpty(userKey)) {
//                    redisCache.deleteObject(userIdKey);
//                    redisCache.deleteObject(userKey);
//                }
//        }
//        // 生成token
//        return tokenService.createToken(loginUser);
//    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }


}
